import os
import time

import cv2
import numpy as np
import pydirectinput
import win32gui

from grabscreen import grab_screen
from nsh_inputkeys import forward_jump


def nsh_boss_blood_count(image):
    # 设定颜色HSV范围，假定为红色
    redLower = (0, 50, 50)
    redUpper = (10, 255, 255)
    # mask = cv2.inRange(hsv_image, lower_range, upper_range)

    # 读取图像
    img = image
    # print(img.shape)

    x, y = 600, 100  # 左上角坐标
    w, h = 800, 30  # 裁剪区域的宽度和高度

    # 执行裁剪
    # 注意：这里的切片操作对灰度图像和彩色图像都是相同的
    cropped_image = img[y:y + h, x:x + w]

    # cv2.imshow('boss_blood_img', cropped_image)

    # 将图像转化为HSV格式
    hsv = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2HSV)

    # 去除颜色范围外的其余颜色
    mask = cv2.inRange(hsv, redLower, redUpper)

    # cv2.imshow('boss_blood_img', mask)

    # 二值化操作
    ret, binary = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)

    # 膨胀操作，因为是对线条进行提取定位，所以腐蚀可能会造成更大间隔的断点，将线条切断，因此仅做膨胀操作
    kernel = np.ones((5, 5), np.uint8)
    dilation = cv2.dilate(binary, kernel, iterations=1)

    # 获取图像轮廓坐标，其中contours为坐标值，此处只检测外形轮廓
    contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    if len(contours) > 0:
        # cv2.boundingRect()返回轮廓矩阵的坐标值，四个值为x, y, w, h， 其中x, y为左上角坐标，w,h为矩阵的宽和高
        boxes = [cv2.boundingRect(c) for c in contours]
        boxes = sorted(boxes, key=lambda x: (-x[2]))
        contour = boxes[0]
        for box in boxes:
            x, y, w, h = box
            # 绘制矩形框对轮廓进行定位
            cv2.rectangle(img, (x, y), (x + w, y + h), (153, 153, 0), 2)
            # # 将绘制的图像保存并展示
            # cv2.imwrite("./img/boss_blood_" + str(time.time()) + ".jpg", img)
            # cv2.imshow('image', img)
        print("boss_blood:" + str(contour[2]))
        return contour[2]
    return -1


def nsh_self_blood_count(img):
    # # 定义绿色的HSV范围（这里使用的是0-179的H范围）
    lower_green = np.array([50, 100, 100])
    upper_green = np.array([100, 255, 255])

    # lower_dark_green = np.array([35, 100, 50])   # 较高的饱和度，较低的亮度
    # upper_dark_green = np.array([70, 255, 100])  # 较高的饱和度，适中的亮度（仍然较低）

    x, y = 750, 1050  # 左上角坐标
    w, h = 250, 50  # 裁剪区域的宽度和高度

    # 执行裁剪
    # 注意：这里的切片操作对灰度图像和彩色图像都是相同的
    cropped_image1 = img[y:y + h, x:x + w]

    # cv2.imshow('self_blood_img', cropped_image1)

    # 将图像转化为HSV格式
    hsv = cv2.cvtColor(cropped_image1, cv2.COLOR_BGR2HSV)

    # 去除颜色范围外的其余颜色
    mask = cv2.inRange(hsv, lower_green, upper_green)
    # mask_dark_green = cv2.inRange(hsv, lower_green, upper_green)
    # mask = cv2.bitwise_or(mask_light_green, mask_dark_green)

    # cv2.imshow('self_blood_img', mask)

    # 二值化操作
    ret, binary = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)

    # 膨胀操作，因为是对线条进行提取定位，所以腐蚀可能会造成更大间隔的断点，将线条切断，因此仅做膨胀操作
    kernel = np.ones((5, 5), np.uint8)
    dilation = cv2.dilate(binary, kernel, iterations=1)

    # 获取图像轮廓坐标，其中contours为坐标值，此处只检测外形轮廓
    contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    if len(contours) > 0:
        # cv2.boundingRect()返回轮廓矩阵的坐标值，四个值为x, y, w, h， 其中x, y为左上角坐标，w,h为矩阵的宽和高

        boxes = [cv2.boundingRect(c) for c in contours]
        boxes = sorted(boxes, key=lambda x: (-x[2]))
        contour = boxes[0]
        for box in boxes:
            x, y, w, h = box
            # 绘制矩形框对轮廓进行定位
            cv2.rectangle(img, (x, y), (x + w, y + h), (153, 153, 0), 2)
            # 将绘制的图像保存并展示
            # cv2.imwrite("./img/self_blood_"+str(time.time())+".jpg", img)
            # cv2.imshow('image', img)
        print("self_blood:" + str(contour[2]))
        return contour[2]
    return -1


def test_find_blool_img():
    # station_size = (0, 0, 1920, 1080)

    station = grab_screen()
    # station = cv2.cvtColor(grab_screen(station_size), cv2.COLOR_BGR2RGB)

    cv2.imshow("station Window", station)
    # collect blood gray graph for count self and boss blood
    boss_blood = nsh_boss_blood_count(station)
    self_blood = nsh_self_blood_count(station)

    # change graph to WIDTH * HEIGHT for station input
    WIDTH = 96
    HEIGHT = 88
    station = cv2.resize(station, (WIDTH, HEIGHT))

    print("boss_blood:" + boss_blood.__str__())
    # print("self_blood:" + self_blood.__str__())
    cv2.waitKey()


def test_blood_procees():
    last_time = time.time()
    while True:

        station = grab_screen()

        boss_blood = nsh_boss_blood_count(station)
        self_blood = nsh_self_blood_count(station)

        # change graph to WIDTH * HEIGHT for station input
        WIDTH = 96
        HEIGHT = 88
        station = cv2.resize(station, (WIDTH, HEIGHT))

        # 测试时间用
        print('loop took {} seconds'.format(time.time() - last_time))
        last_time = time.time()

        if cv2.waitKey(5) & 0xFF == ord('q') or boss_blood == -1:
            break


def restart_boss():

    hwnd = win32gui.FindWindow(None, "MuMu模拟器12")
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)

    # 点击退出副本按钮
    pydirectinput.moveTo(left + 1635, top + 250)
    pydirectinput.click(left + 1635, top + 250)
    time.sleep(2)
    pydirectinput.press('enter')

    # 等待a
    print("等待5s...")
    time.sleep(10)

    print("准备进入副本")

    # 菜单

    pydirectinput.press('esc')

    # 副本
    # pydirectinput.moveTo(left + 1545, top + 500)
    pydirectinput.click(left + 1545, top + 500)
    time.sleep(1)


    # 4boss
    pydirectinput.moveTo(left + 1700, top + 600)
    pydirectinput.click(left + 1700, top + 600)
    time.sleep(1)


    # 组队
    pydirectinput.moveTo(left + 1600, top + 550)
    pydirectinput.doubleClick(x=left + 1600, y=top + 550)
    time.sleep(1)

    # 开始
    pydirectinput.moveTo(left + 1750, top + 1000)
    pydirectinput.doubleClick(left + 1750, top + 1000)
    time.sleep(3)

    # 就绪
    pydirectinput.moveTo(left + 1550, top + 850)
    pydirectinput.click(left + 1550, top + 850)
    time.sleep(1)

    # 等待
    print("等待进入副本..")
    time.sleep(15)

    pydirectinput.moveTo(left + 980, top + 645)
    pydirectinput.click()
    time.sleep(1)

    # 确认
    pydirectinput.click(left + 933, top + 715)



    # 设置队友
    time.sleep(5)
    print("人机需要设置队友..")


    # 前进

    forward_jump()
    forward_jump()
    pydirectinput.press('tab')

    # 锁定boss
    pydirectinput.press('tab')


if __name__ == '__main__':
    wait_time = 2
    for i in list(range(wait_time))[::-1]:
        print(i + 1)
        time.sleep(1)
        # forward_jump(1)

    restart_boss()


def test_img_deal():
    image = 'test.png'
    savefile = './mark1'
    # image = os.listdir(image_file)
    save_image = os.path.join(savefile, image)

    # 设定颜色HSV范围，假定为红色
    redLower = (0, 50, 50)
    redUpper = (10, 255, 255)
    # mask = cv2.inRange(hsv_image, lower_range, upper_range)

    # 读取图像
    img = cv2.imread(image)
    print(img.shape)

    x, y = 0, 0  # 左上角坐标
    w, h = 1000, 100  # 裁剪区域的宽度和高度

    # 执行裁剪
    # 注意：这里的切片操作对灰度图像和彩色图像都是相同的
    cropped_image = img[y:y + h, x:x + w]

    # 将图像转化为HSV格式
    hsv = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2HSV)

    # 去除颜色范围外的其余颜色
    mask = cv2.inRange(hsv, redLower, redUpper)

    cv2.imshow('image1', mask)

    # 二值化操作
    ret, binary = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)

    # 膨胀操作，因为是对线条进行提取定位，所以腐蚀可能会造成更大间隔的断点，将线条切断，因此仅做膨胀操作
    kernel = np.ones((5, 5), np.uint8)
    dilation = cv2.dilate(binary, kernel, iterations=1)

    # 获取图像轮廓坐标，其中contours为坐标值，此处只检测外形轮廓
    contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    if len(contours) > 0:
        # cv2.boundingRect()返回轮廓矩阵的坐标值，四个值为x, y, w, h， 其中x, y为左上角坐标，w,h为矩阵的宽和高
        boxes = [cv2.boundingRect(c) for c in contours]
        for box in boxes:
            x, y, w, h = box
            # 绘制矩形框对轮廓进行定位
            cv2.rectangle(img, (x, y), (x + w, y + h), (153, 153, 0), 2)
            # 将绘制的图像保存并展示
            cv2.imwrite(save_image, img)
            cv2.imshow('image', img)
            print("boss blood:" + str(w))

    cv2.waitKey()

    # # 定义绿色的HSV范围（这里使用的是0-179的H范围）
    lower_green = np.array([50, 100, 100])
    upper_green = np.array([100, 255, 255])

    # lower_dark_green = np.array([35, 100, 50])   # 较高的饱和度，较低的亮度
    # upper_dark_green = np.array([70, 255, 100])  # 较高的饱和度，适中的亮度（仍然较低）

    x, y = 220, 1210  # 左上角坐标
    xs, ys = 220, 1210  # 左上角坐标
    w, h = 250, 50  # 裁剪区域的宽度和高度

    # 执行裁剪
    # 注意：这里的切片操作对灰度图像和彩色图像都是相同的
    cropped_image1 = img[y:y + h, x:x + w]

    cv2.imshow('image_m', cropped_image1)

    # 将图像转化为HSV格式
    hsv = cv2.cvtColor(cropped_image1, cv2.COLOR_BGR2HSV)

    # 去除颜色范围外的其余颜色
    mask = cv2.inRange(hsv, lower_green, upper_green)
    # mask_dark_green = cv2.inRange(hsv, lower_green, upper_green)
    # mask = cv2.bitwise_or(mask_light_green, mask_dark_green)

    cv2.imshow('image2', mask)

    # 二值化操作
    ret, binary = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)

    # 膨胀操作，因为是对线条进行提取定位，所以腐蚀可能会造成更大间隔的断点，将线条切断，因此仅做膨胀操作
    kernel = np.ones((5, 5), np.uint8)
    dilation = cv2.dilate(binary, kernel, iterations=1)

    # 获取图像轮廓坐标，其中contours为坐标值，此处只检测外形轮廓
    contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    if len(contours) > 0:
        # cv2.boundingRect()返回轮廓矩阵的坐标值，四个值为x, y, w, h， 其中x, y为左上角坐标，w,h为矩阵的宽和高
        boxes = [cv2.boundingRect(c) for c in contours]
        for box in boxes:
            x, y, w, h = box
            # 绘制矩形框对轮廓进行定位
            cv2.rectangle(img, (x, y), (x + w, y + h), (153, 153, 0), 2)
            # 将绘制的图像保存并展示
            cv2.imwrite(save_image, img)
            cv2.imshow('image', img)
            print("self blood:" + str(w))

    cv2.waitKey()

    # 视频结束后，按任意键退出
    cv2.destroyAllWindows()
